/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.dao;

import java.util.HashMap;
import java.util.Map;

import net.martinimix.beans.bind.BindingService;

import com.bluemartini.dna.DNAList;

/**
 * Provides a simple template for executing business actions that require no input
 * and respond with only a single business object.
 * 
 * @author Scott Rossillo
 *
 */
public class SimpleBusinessActionTemplate extends BusinessActionTemplate {

	private final static Object BOGUS = new Object();
	
	/**
	 * Creates a new simple business action template.
	 * 
	 * @param bindingService
	 */
	public SimpleBusinessActionTemplate(BindingService bindingService) {
		super(bindingService);
	}
	
	/**
	 * Creates a new simple business action template without setting a
	 * binding service.  Subclasses are expected to set a binding service
	 * prior to executing business actions.
	 */
	protected SimpleBusinessActionTemplate() { }
	
	public Object executeWithoutInput(String action, Object target, String returnType) {
		
		DNAList in = new DNAList();
		in.setList("formData", new DNAList());
		
		return this.execute(action, target, returnType, in);
	}
	
	public void executeWithoutOutput(String action, Object source, String type) {
		
		Map input = new HashMap();
		
		input.put(type, source);
		this.executeWithoutOutput(action, input, type);
	}
	
	public void executeWithoutOutput(String action, Map input, String returnType) {
		
		this.execute(action, BOGUS, returnType, createBusinessActionInput(input, false));
	}
	
	/**
	 * Executes the given action and binds the response to the given target.
	 * 
	 * @param action the name of the business action to execute
	 * 
	 * @param target the <code>Object</code> to bind
	 * 
	 * @param returnType the
	 *  
	 * @return 
	 */
	protected Object execute(String action, Object target, String returnType, DNAList input) {
		
		DNAList response;
		
		response = super.executeInternal(action, input);
		
		return bindingService.bindBean(response.removeBusinessObject(returnType), target);
	}
	
	/**
	 * @param action
	 * @param target
	 * @param returnType
	 * @param input
	 * @return
	 */
	public Object execute(String action, Object target, String returnType, Map input) {
		
		return execute(action, target, returnType, createBusinessActionInput(input, true));
	}

}
